use chrono::{DateTime, Local};
use shq_common::prelude::get_my_pool;

use super::cache::{FlowCache, SaveType, ExecutorInfo};
use sqlx::Row;

pub(super) async fn get_user_from_running(
    run_id: u64,
    step_id: u8,
    tx: Option<&mut sqlx::Transaction<'_, sqlx::MySql>>,
) -> anyhow::Result<Vec<ExecutorInfo>> {
    let mut fuc = FlowCache::from(run_id)?;
    let mut uids = fuc.get_step_users(step_id)?;
    if uids.is_empty() {
        let sql="SELECT emid,state,start_time,submit_time,feed_back FROM flow_run_step WHERE run_id=? and step_id=?";
        let query = sqlx::query(sql)
            .bind(run_id)
            .bind(step_id);
        let rows = if let Some(tx) = tx {
            query.fetch_all(&mut **tx).await?
        } else {
            query.fetch_all(get_my_pool()).await?
        };
        for row in rows.into_iter() {
            let uid: u32 = row.try_get(0)?;
            let st: u8 = row.try_get(1)?;
            let start_time: Option<DateTime<Local>> = row.try_get(2)?;
            let submit_time: Option<DateTime<Local>> = row.try_get(3)?;
            let feed_back: Option<String> = row.try_get(4)?;
            uids.push(ExecutorInfo {
                user_id: uid,
                task_state: st.into(),
                start_time,
                submit_time,
                feed_back,
                save_type: SaveType::None,
            });
        }
        if !uids.is_empty() {
            fuc.set_step_users(step_id, &uids)?;
        }
    }
    Ok(uids)
}
